package org.gongliang.jsmile.config.oss.cloud;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.DirectoryFileFilter;
import org.apache.commons.io.filefilter.FileFilterUtils;
import org.gongliang.jsmile.common.enums.KException;
import org.gongliang.jsmile.common.exception.JSmileException;
import org.gongliang.jsmile.common.kit.StrKit;
import org.gongliang.jsmile.config.oss.OSSConfig;
import org.gongliang.jsmile.config.oss.OSSService;

import com.google.common.collect.Lists;

import jodd.io.FileUtil;

/**
 * 自定义nginx文件服务器
 * 
 * @author 亮仔
 *
 */
public class NginxService extends OSSService {

	public NginxService() {
		this.config = OSSConfig.me();
	}

	@Override
	public String upload(byte[] data, String path) {
		return upload(new ByteArrayInputStream(data), path);
	}

	@Override
	public String upload(InputStream inputStream, String path) {
		String f = config.getNginxUploadPath() + path;
		f = f.substring(0, f.lastIndexOf("/"));
		File localFile = new File(f);
		try {
			if (!localFile.exists() && !localFile.isDirectory()) {
				localFile.mkdirs();
			}
			FileUtils.copyInputStreamToFile(inputStream, new File(config.getNginxUploadPath() + path));
			// file.transferTo(new File(config.getNginxUploadPath() + path));
		} catch (Exception e) {
			throw new JSmileException(KException.FILE_UPLOAD_ERROR, e);
		}
		return config.getNginxDownPath() + path;
	}

	@Override
	public String down(String path, String localPath) {
		return config.getNginxDownPath() + path;
	}

	@Override
	public void delete(String path) {
		try {
			FileUtil.delete(config.getNginxUploadPath() + path);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public List<String> listFiles(String path) {
		OSSConfig config = OSSConfig.me();
		List<String> urls = Lists.newArrayList();
		String filename = OSSConfig.me().getNginxUploadPath() + path;
		File file = new File(filename);
		if (!file.exists() && !file.isDirectory())
			file.mkdirs();
		Collection<File> list = FileUtils.listFiles(file, FileFilterUtils.suffixFileFilter(""),
				DirectoryFileFilter.INSTANCE);
		for (File f : list) {
			String tem = f.getAbsolutePath();
			if (StrKit.isWindows()) {
				tem = tem.replaceAll("\\\\", "/");
			}
			tem = tem.replaceAll(config.getNginxUploadPath(), config.getNginxDownPath());
			urls.add(tem);
		}
		return urls;
	}
}
